package com.ymt.fmd.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class JerseyRestClient {
	
	private Logger logger = Logger.getLogger(JerseyRestClient.class.getName());
	private Client client;
	
	public JerseyRestClient() {
		ClientConfig cc = new DefaultClientConfig();
		cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
		client = Client.create(cc);
	}
	
	public String get(String url) {
		try {
			logger.finest("GET URL:" + url);
			WebResource wr = client.resource(UriBuilder.fromUri(url).build());
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
			return response;
		} finally {
			client.destroy();
		}
	}
	
	public String get(String url, Map<String, String> params) throws UnsupportedEncodingException {
		try {
			if (params!=null) {
				StringBuilder sb = new StringBuilder(url);
				sb.append(sb.indexOf("?")>=0 ? '&' : '?');
				int count = 0;
				for (Entry<String, String> param : params.entrySet()) {
					if (count++>0) {
						sb.append('&');
					}
					sb.append(param.getKey()).append('=')
						.append(param.getValue()!=null ? URLEncoder.encode(param.getValue(), Const.ENCODING) : "");
				}
				url = sb.toString();
			}
			logger.finest("GET URL:" + url);
			WebResource wr = client.resource(UriBuilder.fromUri(url).build());
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
			return response;
		} finally {
			client.destroy();
		}
	}
	
	public String delete(String url, Map<String, String> params) throws UnsupportedEncodingException {
		try {
			if (params!=null) {
				StringBuilder sb = new StringBuilder(url);
				sb.append(sb.indexOf("?")>=0 ? '&' : '?');
				int count = 0;
				for (Entry<String, String> param : params.entrySet()) {
					if (count++>0) {
						sb.append('&');
					}
					sb.append(param.getKey()).append('=')
						.append(param.getValue()!=null ? URLEncoder.encode(param.getValue(), Const.ENCODING) : "");
				}
				url = sb.toString();
			}
			logger.finest("DELETE URL:" + url);
			WebResource wr = client.resource(UriBuilder.fromUri(url).build());
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE).delete(String.class);
			return response;
		} finally {
			client.destroy();
		}
	}
	
	public String post(String url, Map<String, String> params) {
		try {
			logger.finest("POST URL:" + url);
			WebResource wr = client.resource(url);
			MultivaluedMap<String, String> map = new MultivaluedMapImpl();
			if (params!=null) {
				for (Entry<String, String> param : params.entrySet()) {
					if (param.getValue()!=null) {
						map.add(param.getKey(), param.getValue().toString());
					}
				}
			}
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE)
					.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class, map);
			return response;
		} finally {
			client.destroy();
		}
	}
    
	public String post(String url, JSONObject params) {
		try {
			logger.finest("POST URL:" + url);
			WebResource wr = client.resource(url);
			MultivaluedMap<String, String> map = new MultivaluedMapImpl();
			if (params!=null) {
				for (Entry<String, Object> param : params.entrySet()) {
					if (param.getValue()!=null) {
						map.add(param.getKey(), param.getValue().toString());
					}
				}
			}
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE)
					.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class, map);
			return response;
		} finally {
			client.destroy();
		}
	}
	
	public String put(String url, Map<String, String> params) {
		try {
			logger.finest("PUT URL:" + url);
			WebResource wr = client.resource(url);
			MultivaluedMap<String, String> map = new MultivaluedMapImpl();
			if (params!=null) {
				for (Entry<String, String> param : params.entrySet()) {
					if (param.getValue()!=null) {
						map.add(param.getKey(), param.getValue().toString());
					}
				}
			}
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE)
					.type(MediaType.APPLICATION_FORM_URLENCODED).put(String.class, map);
			return response;
		} finally {
			client.destroy();
		}
	}
	
	public String put(String url, JSONObject params) {
		try {
			logger.finest("PUT URL:" + url);
			WebResource wr = client.resource(url);
			MultivaluedMap<String, String> map = new MultivaluedMapImpl();
			if (params!=null) {
				for (Entry<String, Object> param : params.entrySet()) {
					if (param.getValue()!=null) {
						map.add(param.getKey(), param.getValue().toString());
					}
				}
			}
			String response = wr.accept(MediaType.APPLICATION_JSON_TYPE)
					.type(MediaType.APPLICATION_FORM_URLENCODED).put(String.class, map);
			return response;
		} finally {
			client.destroy();
		}
	}

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		JerseyRestClient c = new JerseyRestClient();
		//String o = c.get("http://localhost:8090/bpmp//servlet/co?action=queryCoTasks");
		
		JSONObject jo = new JSONObject();
		jo.put("aaa", "postpost");
		jo.put("fromRow", "200");
		
		Map<String, String> jo1 = new HashMap<String, String>();
		jo1.put("params", "getget");
		jo1.put("fromRow", "100");
		//String o = c.get("http://localhost:8090/bpmp/openrest/co/testget/id1", jo1);
		//String o = c.post("http://localhost:8090/bpmp/openrest/co/test", jo);
		//String o = c.put("http://localhost:8090/bpmp/openrest/co/testdel", jo);
		String o = c.delete("http://localhost:8090/bpmp/openrest/co/testdel", jo1);
	}

}
